/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "plugins/ecmascript/runtime/mem/ecma_string.h"

#include <cmath>
#include <cstdlib>

#include "plugins/ecmascript/runtime/ecma_string-inl.h"
#include "plugins/ecmascript/runtime/js_symbol.h"
#include "libpandabase/macros.h"

namespace ark::ecmascript {
template <class T>
PandaString ConvertToPandaString(T sp)
{
    PandaString res;
    res.reserve(sp.size());

    // Also support ascii that great than 127, so using unsigned char here
    constexpr size_t MAX_CHAR = std::numeric_limits<unsigned char>::max();

    for (const auto &c : sp) {
        if (c > MAX_CHAR) {
            return "";
        }
        res.push_back(c);
    }

    return res;
}

PandaString ConvertToPandaString(const ecmascript::EcmaString *s, StringConvertedUsage usage)
{
    if (s == nullptr) {
        return PandaString("");
    }
    return ConvertToPandaString(s, 0, s->GetLength(), usage);
}

PandaString ConvertToPandaString(const EcmaString *s, uint32_t start, uint32_t length, StringConvertedUsage usage)
{
    if (s == nullptr) {
        return PandaString("");
    }
    if (s->IsUtf16()) {
        // Should convert utf-16 to utf-8, because uint16_t likely great than maxChar, will convert fail
        bool modify = (usage != StringConvertedUsage::PRINT);
        // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
        size_t len = utf::Utf16ToUtf8Size(s->GetDataUtf16() + start, length, modify) - 1;
        PandaVector<uint8_t> buf(len);
        // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
        len = utf::ConvertRegionUtf16ToUtf8(s->GetDataUtf16() + start, buf.data(), length, len, 0, modify);
        Span<const uint8_t> sp(buf.data(), len);
        return ConvertToPandaString(sp);
    }

    Span<const uint8_t> sp(s->GetDataUtf8(), s->GetLength());
    return ConvertToPandaString(sp.SubSpan(start, length));
}
}  // namespace ark::ecmascript
